package com.notice.repository;

import com.notice.model.UserModel;
import com.notice.dao.UserDao;
import com.notice.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Repository
public class UserRepository {
    
    @Autowired
    private UserDao userDao;
    
    public UserModel findByUidAndPassword(String uid, String password) {
        User query = new User();
        query.setUid(uid != null ? uid : "");
        query.setPassword(password != null ? password : "");
        List<User> users = userDao.Find(query);
        
        if (users != null && !users.isEmpty()) {
            return convertToModel(users.get(0));
        }
        return null;
    }
    
    public List<UserModel> findAll() {
        List<User> users = userDao.FindAll();
        return users != null ? users.stream()
                .map(this::convertToModel)
                .collect(Collectors.toList()) 
                : new ArrayList<>();
    }
    
    public boolean save(UserModel user) {
        if (user == null) return false;
        return userDao.AddUser(convertToEntity(user)) > 0;
    }
    
    public boolean delete(String uid) {
        if (uid == null || uid.trim().isEmpty()) return false;
        return userDao.Delete(uid) > 0;
    }
    
    public boolean update(UserModel user) {
        if (user == null || user.getUid() == null) return false;
        return userDao.Update(convertToEntity(user)) > 0;
    }
    
    private User convertToEntity(UserModel model) {
        if (model == null) return null;
        
        User entity = new User();
        entity.setUid(model.getUid() != null ? model.getUid() : "");
        entity.setPassword(model.getPassword() != null ? model.getPassword() : "");
        entity.setUtype(Integer.valueOf(model.getUtype() == null ? 0 : model.getUtype()));
        entity.setAge(Integer.valueOf(model.getAge() == null ? 0 : model.getAge()));
        entity.setSex(Integer.valueOf(model.getSex() == null ? 0 : model.getSex()));
        entity.setHeadphoto(model.getHeadphoto() != null ? model.getHeadphoto() : "");
        return entity;
    }
    
    private UserModel convertToModel(User entity) {
        if (entity == null) return null;
        
        UserModel model = new UserModel();
        model.setUid(entity.getUid() != null ? entity.getUid() : "");
        model.setPassword(entity.getPassword() != null ? entity.getPassword() : "");
        model.setUtype(entity.getUtype());
        model.setAge(entity.getAge());
        model.setSex(entity.getSex());
        model.setHeadphoto(entity.getHeadphoto() != null ? entity.getHeadphoto() : "");
        return model;
    }
} 